<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Album;
use App\Models\AlbumImage;
use App\Models\Activity;
use App\Org\Developer\Helper;
use App\Org\Developer\JsonReturnInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * @author 陈玉琦
 * 大屏幕
 */
class ScreenController extends Controller
{
    private $fields = ['id', 'user_id', 'type', 'title', 'bg_image_url', 'start_time', 'end_time'];

    /**
     * Display a listing of the resource.
     *
     * @return array
     */
    public function index(Request $request)
    {
        // 用户 user_id
        //if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
        //    return JsonReturnInfo::ID_ERROR;
        //}

        // 活动 activity_id
        if (Helper::idInvalid($activity_id = $request->input('activity_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        try {
            $data = AlbumImage::select(['album_images.id', 'album_images.album_id', 'album_images.image_url', 'albums.album_type_id'])
                ->join('albums', function ($join) {
                    $join->on('albums.id', '=', 'album_images.album_id');
                })
                ->where('album_images.album_id', function($query) use ($activity_id) {
                    $query->select('id')->from('albums')->where(['activity_id' => $activity_id]);
                })
                ->get();
            return JsonReturnInfo::infoSuccess('大屏幕相册数据获取成功.', $data);
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function store(Request $request)
    {
        // 用户 user_id
        if (Helper::idInvalid($activityData['user_id'] = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 活动的标题
        if (empty($activityData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        $activityData['type'] = 'screen';

        // 用户创建大屏幕相册选择的相册类型
        if (Helper::idInvalid($album_type_id = $request->input('album_type_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 大屏幕相册的图片数组，请求接口时传递是数组
        if (empty($screenAlbum = $request->input('activity_screen', ''))) {
            return JsonReturnInfo::infoEmpty('activity_screen');
        }
        // 为了尽可能的灵活性，相册表 album 一条记录是放一个图片
        $screenArray = json_decode($screenAlbum, true);

        try {
            $activity_id = 0;

            // 一个用户可以创建重复的活动，比如关于 xxx 的投票，所以不必进行重复性校验。
            // 可以直接写入活动信息
            $createModel = Activity::create($activityData);
            if (isset($createModel) && ($activity_id = $createModel->id)) {

                // 创建相册
                $albumModel = Album::create(['activity_id' => $activity_id, 'album_type_id' => $album_type_id]);
                if (!(isset($albumModel) && $albumModel->id)) {
                    return JsonReturnInfo::infoFailure('活动创建失败（相册创建失败）');
                }

                // 保存相册的图片
                if (!empty($screenArray)) {
                    // 批量新增
                    $batch = [];
                    foreach ($screenArray as $val) {
                        $batch[] = [
                            'album_id' => $albumModel->id,
                            'image_url' => $val
                        ];
                    }
                    $result = AlbumImage::insert($batch);
                    if (!$result) {
                        return JsonReturnInfo::infoFailure('活动创建失败.');
                    }
                }
                return JsonReturnInfo::infoSuccess('活动创建成功.', ['activity_id' => $activity_id]);
            }
            return JsonReturnInfo::infoFailure('活动创建失败.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return array
     */
    public function update(Request $request, $id)
    {
        // 活动 activity_id 是否合法
        if (Helper::idInvalid($id)) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 用户 user_id
        if (Helper::idInvalid($user_id = $request->input('user_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 用户创建大屏幕相册选择的相册类型
        if (Helper::idInvalid($album_type_id = $request->input('album_type_id', 0))) {
            return JsonReturnInfo::ID_ERROR;
        }

        // 活动的标题
        if (empty($activityData['title'] = $request->input('title', ''))) {
            return JsonReturnInfo::infoEmpty('title');
        }

        // 大屏幕相册的图片数组，请求接口时传递是数组
        if (empty($screenAlbum = $request->input('activity_screen', ''))) {
            return JsonReturnInfo::infoEmpty('activity_screen');
        }
        // 为了尽可能的灵活性，相册表 album 一条记录是放一个图片
        $screenArray = json_decode($screenAlbum, true);
        
        try {
            
            // 必须存在且必须是用户自己的资源
            $activityModel = Activity::select($this->fields)->where(['id' => $id])->first();
            if (!(isset($activityModel) && $activityModel->id)) {
                return JsonReturnInfo::infoFailure('要修改的活动不存在.');
            }
            if (!Helper::isUserSelfResource($user_id, $activityModel->user_id)) {
                return JsonReturnInfo::NOT_SELF_RESOURCE_ERROR;
            }

            $activityModel->title = $activityData['title'];

            $result = $activityModel->save();
            if (!$result) {
                return JsonReturnInfo::infoFailure('活动修改失败.');
            }

            // 更新相册表，可能会失败，因为数据没有改变
            $albumModel = Album::select(['id', 'album_type_id'])->where(['activity_id' => $activity_id])->first();
            if (isset($albumModel) && $albumModel->id) {
                $albumModel->album_type_id = $album_type_id;
                $albumModel->save();
            } 
            // 没有则新建
            else {
                $albumModel = Album::create(['activity_id' => $id, 'album_type_id' => $album_type_id]);
                if (!(isset($albumModel) && $albumModel->id)) {
                    return JsonReturnInfo::infoFailure('活动修改失败（相册创建失败）.');
                }
            }

            // 保存相册的图片
            if (!empty($screenArray)) {
                // 批量新增
                $batch = [];
                foreach ($screenArray as $val) {
                    $batch[] = [
                        'album_id' => $albumModel->id,
                        'image_url' => $val
                    ];
                }
                $result = AlbumImage::insert($batch);
                if (!$result) {
                    return JsonReturnInfo::infoFailure('活动修改失败.');
                }
            }
            return JsonReturnInfo::infoSuccess('活动修改成功.');
        } catch (\Exception $e) {
            return JsonReturnInfo::infoCatch($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
